package com.sinsz.nacos.context;

import com.sinsz.nacos.ClassUtils;
import com.sinsz.nacos.annotation.NacosLoader;
import com.sinsz.nacos.listener.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.NonNull;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载指定包中的所有类
 *
 * @author chenjianbo
 * @date 2019-1-30
 */
public class NacosLoaderRegistrar implements ImportBeanDefinitionRegistrar {

    private static final Logger logger = LoggerFactory.getLogger(NacosLoaderRegistrar.class);

    @Override
    public void registerBeanDefinitions(@NonNull AnnotationMetadata metadata, @NonNull BeanDefinitionRegistry registry) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(NacosLoader.class.getName()));
        if (attributes.isEmpty()) {
            return;
        }
        String[] packages = attributes.getStringArray("value");
        if (packages.length <= 0) {
            return;
        }
        List<Class<?>> classes = new ArrayList<>();
        try {
            for (String aPackage : packages) {
                classes.addAll(ClassUtils.getAllClassByPackageName(Package.getPackage(aPackage)));
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            logger.error("load beans error! {}", e.getCause());
        }
        Cache.allClasses = classes;
    }

}